package org.rcgwt.client.ui.validator.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.rcgwt.client.ui.validator.IChecker;
import org.rcgwt.client.ui.validator.IClientValidatorContext;
import org.rcgwt.client.ui.validator.messages.Severity;
import org.rcgwt.client.util.Pattern;

/**
 * A checker which checks an email address structure like .@."."(fr|eu|com...)
 * 
 * @author Elian ORIOU
 * 
 */

public class EmailChecker implements IChecker {

	private final Pattern EMAIL_PATTERN;

	private List<String> accepted_extensions;
	private boolean isFilteredExtension = false;

	public EmailChecker(Map<String, String> parameters) {
		EMAIL_PATTERN = Pattern.compile("^(.+)@(.+)[.]{1}([a-zA-Z]{2,6})$");

		if (parameters.containsKey("email.accepted_extension") == true) {
			accepted_extensions = new ArrayList<String>();
			String ext = parameters.get("email.accepted_extension");
			String[] exts = ext.split("[,]|[.]");
			for (String e : exts) {
				accepted_extensions.add(e);
			}
			isFilteredExtension = true;
		}
	}

	@Override
	public boolean check(IClientValidatorContext context, String s) {
		if (EMAIL_PATTERN.matches(s)) {
			if (isFilteredExtension == true) {
				String e = s.substring(s.lastIndexOf("."));
				if (accepted_extensions.contains(e) == true) {
					return true;
				} else {
					launchInvalidExtensionError(context);
					return false;
				}
			}
			return true;
		} else {
			context.addMessage(context.getMessagesProvider()
					.StructureErrorShort(), context.getMessagesProvider()
					.StructureError(), Severity.ERROR);
			return false;
		}
	}

	private void launchInvalidExtensionError(IClientValidatorContext context) {
		context.addMessage(context.getMessagesProvider()
				.InvalidExtensionErrorShort(accepted_extensions.toString()),
				context.getMessagesProvider().InvalidExtensionError(
						accepted_extensions.toString()), Severity.ERROR);
	}
}
